package com.xxx.meter.ui.info;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.xxx.meter.R;
import com.xxx.meter.base.BaseActivity;
import com.xxx.meter.model.http.Api;
import com.xxx.meter.model.http.ApiCallback;
import com.xxx.meter.model.http.bean.PatrolRecordListBean;
import com.xxx.meter.model.http.bean.base.PageBean;
import com.xxx.meter.model.utils.ButtonUtil;
import com.xxx.meter.model.utils.ToastUtil;
import com.xxx.meter.ui.info.adapter.InfoPatrolListAdapter;
import com.xxx.meter.ui.main.view.DatePickerView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class PatrolRecordActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener, DatePickerDialog.OnDateSetListener {

    @BindView(R.id.main_title)
    TextView mTitle;
    @BindView(R.id.main_recycler)
    RecyclerView mRecycler;
    @BindView(R.id.main_refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.not_data)
    ImageView mNotData;
    @BindView(R.id.not_net)
    ImageView mNotNet;

    @BindView(R.id.main_1)
    FrameLayout m1;
    @BindView(R.id.info_machine_2)
    RelativeLayout m2;

    @BindView(R.id.info_machine_startTime)
    TextView mStartTime;
    @BindView(R.id.info_machine_endTime)
    TextView mEndTime;

    private List<PatrolRecordListBean> mList = new ArrayList<>();
    private InfoPatrolListAdapter mAdapter;
    private int page = 1;

    private DatePickerDialog mDatePickerDialog;
    private SimpleDateFormat simpleDateFormat;

    private long startTime; //开始时间
    private long endTime;   //结束时间
    private boolean isSetTime;  //是否正在设置时间

    private static final int START_TAG = 1;
    private static final int END_TAG = 2;
    private int tag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patrol_record;
    }

    @SuppressLint("SimpleDateFormat")
    @Override
    protected void initData() {
        mTitle.setText("巡机记录");

        mAdapter = new InfoPatrolListAdapter(mList);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.setAdapter(mAdapter);
        mRefresh.setOnRefreshListener(this);
        mAdapter.setOnLoadMoreListener(this, mRecycler);
        mAdapter.setOnItemClickListener(this);

        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        mDatePickerDialog = DatePickerView.showDataPicket(this, this);

        //初始化时间
        endTime = System.currentTimeMillis();
        startTime = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
        mStartTime.setText(simpleDateFormat.format(startTime));
        mEndTime.setText(simpleDateFormat.format(endTime));

        loadInfo(true);
    }

    @OnClick({R.id.main_return, R.id.info_machine_btn, R.id.info_machine_startTime, R.id.info_machine_endTime, R.id.info_machine_record, R.id.not_data, R.id.not_net})
    public void OnClick(View view) {
        if (ButtonUtil.isFastClick()) return;
        switch (view.getId()) {
            case R.id.main_return:
                if (isSetTime) {
                    m1.setVisibility(View.VISIBLE);
                    m2.setVisibility(View.GONE);
                    isSetTime = false;
                } else {
                    finish();
                }
                break;
            case R.id.info_machine_startTime:
                tag = START_TAG;
                mDatePickerDialog.setTitle("选择结束时间");
                String format = simpleDateFormat.format(startTime);
                String[] split = format.split("-");
                if (split.length == 3) {
                    mDatePickerDialog.updateDate(
                            Integer.parseInt(split[0]),
                            Integer.parseInt(split[1]) - 1,
                            Integer.parseInt(split[2])
                    );
                }
                mDatePickerDialog.show();
                break;
            case R.id.info_machine_endTime:
                tag = END_TAG;
                String format1 = simpleDateFormat.format(endTime);
                String[] split1 = format1.split("-");
                if (split1.length == 3) {
                    mDatePickerDialog.updateDate(
                            Integer.parseInt(split1[0]),
                            Integer.parseInt(split1[1]) - 1,
                            Integer.parseInt(split1[2])
                    );
                }
                mDatePickerDialog.setTitle("选择结束时间");
                mDatePickerDialog.show();
                break;
            case R.id.info_machine_record:
                m1.setVisibility(View.GONE);
                m2.setVisibility(View.VISIBLE);
                isSetTime = true;
                break;
            case R.id.info_machine_btn:
                if (startTime == 0) {
                    ToastUtil.showToast("请选择开始时间");
                    return;
                }
                if (endTime == 0) {
                    ToastUtil.showToast("请选择结束时间");
                    return;
                }
                mList.clear();
                mAdapter.notifyDataSetChanged();
                m1.setVisibility(View.VISIBLE);
                m2.setVisibility(View.GONE);
                isSetTime = false;
                loadInfo(true);
                break;
            case R.id.not_data:
                onRefresh();
                break;
            case R.id.not_net:
                onRefresh();
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (ButtonUtil.isFastClick()) return;
        Intent intent = new Intent(this, PatrolRecordDetailActivity.class);
        intent.putExtra("recordId", mList.get(position).getId());
        intent.putExtra("name", mList.get(position).getUserName());
        startActivity(intent);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        long time;
        String timeStr;
        try {
            timeStr = year + "-" + (month + 1) + "-" + dayOfMonth;
            time = simpleDateFormat.parse(timeStr).getTime();
        } catch (ParseException e) {
            ToastUtil.showToast("时间选择错误");
            return;
        }

        switch (tag) {
            case START_TAG:
                startTime = time;
                mStartTime.setText("开始时间" + timeStr);
                break;
            case END_TAG:
                endTime = time;
                mEndTime.setText("结束时间" + timeStr);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (isSetTime) {
            m1.setVisibility(View.VISIBLE);
            m2.setVisibility(View.GONE);
            isSetTime = false;
        } else {
            finish();
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        loadInfo(false);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        loadInfo(false);
    }


    /**
     * @param isRefresh 是否刷新
     * @Model 获取机器巡查数据
     */
    private void loadInfo(boolean isRefresh) {
        Api.getInstance().getPatrolRecordList(startTime, endTime, page, 20)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<PageBean<PatrolRecordListBean>>(this, isRefresh) {
                    @Override
                    public void onSuccess(PageBean<PatrolRecordListBean> beanPageBean) {
                        List<PatrolRecordListBean> list;
                        if (beanPageBean == null || (list = beanPageBean.getList()) == null || list.size() == 0 && page == 1) {
                            mRefresh.setVisibility(View.GONE);
                            mNotData.setVisibility(View.VISIBLE);
                            mNotNet.setVisibility(View.GONE);
                            mRefresh.setRefreshing(false);
                            mAdapter.loadMoreEnd(true);
                            return;
                        }

                        mRefresh.setVisibility(View.VISIBLE);
                        mNotData.setVisibility(View.GONE);
                        mNotNet.setVisibility(View.GONE);
                        if (page == 1) {
                            mList.clear();
                        }
                        mList.addAll(list);
                        if (list.size() < 20) {
                            mAdapter.loadMoreEnd(true);
                        } else {
                            mAdapter.loadMoreComplete();
                        }
                        mRefresh.setRefreshing(false);
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        mRefresh.setVisibility(View.GONE);
                        mNotData.setVisibility(View.GONE);
                        mNotNet.setVisibility(View.VISIBLE);
                        mRefresh.setRefreshing(false);
                        mAdapter.loadMoreEnd(true);
                    }
                });
    }

}
